import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
// 引入 pinia 创建的 store
import { useUserStore } from '@/stores/user'
// import { createPinia } from 'pinia'
// const pinia = createPinia()

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL), // 修改此行
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/home/HomePage.vue'),
      redirect: '/mainContent', // 重定向到更清晰的路径
      children: [
        {
          path: 'mainContent', // 建议路径名与页面功能匹配
          name: 'MainContent',
          component: () => import('@/views/home/MainContent.vue')
        },
        {
          path: 'shoppingCart',
          name: 'ShoppingCart',
          component: () => import('@/views/order/Cart.vue')
        },
        {
          path: 'bookSearch',
          name: 'BookSearch',
          component: () => import('@/views/book/BookSearch.vue')
        },

        {
          path: 'bookDetail/:bookId',
          name: 'BookDetail',
          component: () => import('@/views/book/BookDetail.vue')
        },
        {
          path: 'myOrderLists',
          name: 'MyOrderList',
          component: () => import('@/views/order/OrderList.vue')
        },
        {
          path: 'userCenter',
          name: 'UserCenter',
          component: () => import('@/views/user/Center.vue')
        },

        {
          path: 'admin',
          name: 'Admin',
          component: () => import('@/views/admin/index.vue'),
          meta: { hideFooter: true },
          redirect: '/admin/userList', // 修正重定向路径
          children: [
            {
              path: 'userList', // 移除绝对路径
              name: 'UserList',
              component: () => import('@/views/admin/userList.vue')
            },
            {
              path: 'userAdd',
              name: 'UserAdd',
              component: () => import('@/views/admin/userAdd.vue')
            },
            {
              path: 'bookList',
              name: 'BookList',
              component: () => import('@/views/admin/bookList.vue')
            },
            {
              path: 'bookAdd',
              name: 'BookAdd',
              component: () => import('@/views/admin/bookAdd.vue')
            },
            {
              path: 'orderList',
              name: 'OrderList',
              component: () => import('@/views/admin/orderList.vue')
            },
            {
              path: 'category',
              name: 'Category',
              component: () => import('@/views/admin/category.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/user/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/user/Register.vue')
    }
  ]
})



// 路由前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  // 1. 定义权限分层
  const guestPaths = ['/login', '/register', '/forgetPassword', '/mainContent', '/bookSearch'];
  const guestRouteNames = ['BookDetail']; // 对应路由的 name
  const isGuestPage = guestPaths.includes(to.path) || guestRouteNames.includes(to.name);

  const isUserPage = ['/shoppingCart', '/myOrderLists', '/userCenter'].includes(to.path)
  const isAdminPage = to.path.startsWith('/admin')

  // 2. 游客页面：直接放行
  if (isGuestPage) {
    next()
    return
  }

  // 3. 非游客页面：校验登录状态
  if (!userStore.isLoggedIn) {
    ElMessage({ type: 'error', message: '请先登录', plain: true })
    next('/login')
    return
  }

  // 4. 登录用户页面：已登录则放行
  if (isUserPage) {
    next()
    return
  }

  // 5. 管理员页面：校验角色
  if (isAdminPage) {
    if (userStore.isAdmin) {
      next()
    } else {
      ElMessage({ type: "error", message: '无管理员权限，无法访问', plain: true })
      next('/') // 或跳转到 403 页面
    }
    return
  }

  // 6. 其他页面（如首页、书籍详情等）：登录用户通用放行
  next()
})

export default router